package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.*;
import com.jzo2o.customer.enums.IsDefaultStatusEnum;
import com.jzo2o.customer.enums.IsDeleteStatusEnum;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
@Slf4j
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Resource
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    /**
     * 新增地址簿
     *
     * @param dto
     */
    @Override
    public void addAddress(AddressBookUpsertReqDTO dto) {
        if (ObjectUtils.isNull(dto)){
            throw new CommonException("无效参数");
        }
        Long userId = UserContext.currentUserId();
        if (ObjectUtils.isNull(userId)){
            throw new CommonException("未登录,请先登录");
        }
        queryIsDefault(userId);
        AddressBook addressBook = BeanUtils.copyBean(dto, AddressBook.class);
        if (ObjectUtils.isNotNull(dto.getLocation())){
            String[] location = dto.getLocation().split(",");
            addressBook.setLon(Double.valueOf(location[0]));
            addressBook.setLat(Double.valueOf(location[1]));
        }
        addressBook.setUserId(userId);
        baseMapper.insert(addressBook);
    }

    private void queryIsDefault(Long userId) {
        List<AddressBook> list = this.lambdaQuery()
                .eq(AddressBook::getIsDefault, IsDefaultStatusEnum.ISDEFAULT.getStatus())
                .eq(AddressBook::getUserId, userId)
                .list();
        if (CollUtils.isNotEmpty(list)){
            for (AddressBook addressBook : list) {
                addressBook.setIsDefault(IsDefaultStatusEnum.NOTDEFAULT.getStatus());
                LambdaUpdateWrapper<AddressBook> updateWrapper = Wrappers.<AddressBook>lambdaUpdate()
                        .eq(AddressBook::getId, addressBook.getId());
                this.update(addressBook,updateWrapper);
            }
        }
    }

    /**
     * 地址薄分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<AddressBook> getAddressByPage(AddressBookPageQueryReqDTO dto) {
        if (ObjectUtils.isNull(dto)){
            throw new CommonException("无效参数");
        }
        Long userId = UserContext.currentUserId();
        if (ObjectUtils.isNull(userId)){
            throw new CommonException("未登录,请先登录");
        }
        Page<AddressBook> page = PageUtils.parsePageQuery(dto, AddressBook.class);
        LambdaQueryWrapper<AddressBook> wrapper = Wrappers.<AddressBook>lambdaQuery()
                .eq(AddressBook::getUserId,userId)
                .eq(AddressBook::getIsDeleted, IsDeleteStatusEnum.NOTDELETED.getStatus());
        Page<AddressBook> addressUserPage = addressBookMapper.selectPage(page, wrapper);

        return PageUtils.toPage(addressUserPage, AddressBook.class);
    }

    /**
     * 修改地址簿
     *
     * @param dto
     */
    @Override
    public void updateAddressById(AddressBookUpsertReqDTO dto,Long id) {
        if (ObjectUtils.isNull(dto)){
            throw new CommonException("无效参数");
        }
        Long userId = UserContext.currentUserId();
        if (ObjectUtils.isNull(userId)){
            throw new CommonException("未登录,请先登录");
        }
        AddressBook addressBook = BeanUtils.copyBean(dto, AddressBook.class);
        if (ObjectUtils.isNotNull(dto.getLocation())){
            String[] location = dto.getLocation().split(",");
            addressBook.setLon(Double.valueOf(location[0]));
            addressBook.setLat(Double.valueOf(location[1]));
        }
        addressBook.setId(id);
        baseMapper.updateById(addressBook);
    }

    /**
     * 地址簿批量删除
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteAddress(List<Long> ids) {
        ArrayList<AddressBook> list = new ArrayList<>();
        for (Long id : ids) {
            AddressBook addressBook = new AddressBook();
            addressBook.setId(id);
            addressBook.setIsDeleted(IsDeleteStatusEnum.DELETED.getStatus());
            list.add(addressBook);
        }
        this.updateBatchById(list);
    }

    /**
     * 设置/取消默认地址
     *
     * @param flag
     * @param id
     */
    @Override
    public void updateDefault(Integer flag, Long id) {
        Long userId = UserContext.currentUserId();
        queryIsDefault(userId);
        AddressBook addressBook = new AddressBook();
        addressBook.setIsDefault(flag);
        LambdaUpdateWrapper<AddressBook> updateWrapper = Wrappers.<AddressBook>lambdaUpdate()
                .eq(AddressBook::getId, id);
        this.update(addressBook,updateWrapper);
    }

    /**
     *获取默认地址
     */
    @Override
    public AddressBook selectDefaultAddress() {
        LambdaQueryWrapper<AddressBook> wrapper = Wrappers.<AddressBook>lambdaQuery()
                .eq(AddressBook::getIsDefault, IsDefaultStatusEnum.ISDEFAULT.getStatus());
        return baseMapper.selectOne(wrapper);
    }
}
